package com.mapaower.job.service.impl;

import com.mapaower.job.dao.JobRepository;
import com.mapaower.job.entity.Job;
import com.mapaower.job.service.JobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 工作职位服务实现类
 * 实现工作职位相关的业务逻辑
 */
@Service
public class JobServiceImpl implements JobService {

    @Autowired
    private JobRepository jobRepository;

    @Override
    public Job createJob(Job job) {
        // 设置默认状态为开放
        job.setStatus(Job.JobStatus.OPEN);
        return jobRepository.save(job);
    }

    @Override
    public Job updateJob(Job job) {
        return jobRepository.save(job);
    }

    @Override
    public Optional<Job> getJobById(Long id) {
        return jobRepository.findById(id);
    }

    @Override
    public List<Job> getJobsByCreatorId(Long creatorId) {
        return jobRepository.findByCreatorId(creatorId);
    }

    @Override
    public List<Job> getOpenJobs() {
        return jobRepository.findByStatus(Job.JobStatus.OPEN);
    }

    @Override
    public List<Job> getRemoteJobs() {
        return jobRepository.findByLocationTypeAndStatus(Job.LocationType.REMOTE, Job.JobStatus.OPEN);
    }

    @Override
    public List<Job> getJobsByTypeAndStatus(Job.JobType type, Job.JobStatus status) {
        return jobRepository.findByTypeAndStatus(type, status);
    }

    @Override
    public List<Job> searchJobs(String keyword) {
        return jobRepository.findByTitleContainingOrDescriptionContaining(keyword, keyword);
    }

    @Override
    public Job updateJobStatus(Long id, Job.JobStatus status) {
        Optional<Job> optionalJob = jobRepository.findById(id);
        if (optionalJob.isPresent()) {
            Job job = optionalJob.get();
            job.setStatus(status);
            return jobRepository.save(job);
        }
        throw new RuntimeException("Job not found with id: " + id);
    }

    @Override
    public void deleteJob(Long id) {
        jobRepository.deleteById(id);
    }
}